package com.feixiang.springbootinit.strategy;
import cn.hutool.json.JSONUtil;
import com.feixiang.springbootinit.common.ErrorCode;
import com.feixiang.springbootinit.exception.BusinessException;
import com.feixiang.springbootinit.model.entity.wechat.QwImageMessage;
import com.feixiang.springbootinit.model.entity.wechat.QwMessage;
import com.feixiang.springbootinit.model.entity.wechat.QwVoiceMessage;
import com.feixiang.springbootinit.model.enums.SessionArchiveMsgTypeEnum;
import com.feixiang.springbootinit.model.vo.wechat.MsgVO;
import com.feixiang.springbootinit.processor.SessionArchiveBatchProcessor;
import com.feixiang.springbootinit.processor.SessionArchiveProcessor;
import com.feixiang.springbootinit.service.FileStorageService;
import com.feixiang.springbootinit.service.QwImageMessageService;
import com.feixiang.springbootinit.utils.BatchSaveUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class ImageMessageStrategy implements MessageProcessingStrategy {

    @Autowired
    private QwImageMessageService imageMessageService;

    @Autowired
    private FileStorageService fileStorageService;
    @Override
    public boolean supports(SessionArchiveMsgTypeEnum msgType) {
        return SessionArchiveMsgTypeEnum.IMAGE == msgType;
    }
    @Override
    public void process(MsgVO msgVO, QwMessage baseMessage) {
        try {
            // 获取当前线程的SDK实例（从ThreadLocal中）,媒体资源需要拉取
            //long sdk = SessionArchiveUtil.getSDK();
            // 直接使用全局SDK实例（需确保线程安全）
            long sdk = SessionArchiveProcessor.getGlobalSdkInstance();
            // 调用文件存储服务
            log.info("处理图片消息");
            log.info("存储图片文件: {}", msgVO.getImage().getMd5sum());
            String storedPath = fileStorageService.storeFile(
                    sdk,
                    msgVO.getImage().getSdkfileid(),
                    msgVO.getImage().getMd5sum(),
                    "png", // 图片扩展名
                    "image" // 子目录
            );
            // 获取访问URL并保存到数据库
            String mediaUrl = fileStorageService.getFileUrl(storedPath);
            QwImageMessage imageMessage = new QwImageMessage();
            imageMessage.setMsgId(msgVO.getMsgid());
            imageMessage.setMediaUrl(mediaUrl);
            imageMessage.setFileSize(msgVO.getImage().getFilesize()); //图片的文件大小
            imageMessage.setCreatedTime(new Date());
            imageMessageService.save(imageMessage);
        } catch (Exception e) {
            log.error("处理图片消息失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "处理图片消息失败");
        }
    }

    @Override
    public void batchProcess(List<QwMessage> baseMessages) {
        if (baseMessages.isEmpty()) {
            log.info("批量处理图片消息: 空列表，无需处理");
            return;
        }
        log.info("开始批量处理图片消息，数量: {}", baseMessages.size());
        long sdk = SessionArchiveBatchProcessor.getGlobalSdkInstance();
        List<QwImageMessage> imageMessages = new ArrayList<>(baseMessages.size());
        Date currentTime = new Date();
        for (QwMessage baseMsg : baseMessages) {
            try {
                // 从基础消息中解析出原始消息对象
                MsgVO msgVO = JSONUtil.toBean(baseMsg.getContent(), MsgVO.class);
                if (msgVO.getImage() == null) {
                    log.warn("图片消息内容为空，msgId: {}", baseMsg.getMsgId());
                    continue;
                }
                // 存储文件
                String storedPath = fileStorageService.storeFile(
                        sdk,
                        msgVO.getImage().getSdkfileid(),
                        msgVO.getImage().getMd5sum(),
                        "png",
                        "image"
                );
                // 构建图片消息实体
                QwImageMessage imageMsg = new QwImageMessage();
                imageMsg.setMsgId(msgVO.getMsgid());
                imageMsg.setMediaUrl(fileStorageService.getFileUrl(storedPath));
                imageMsg.setFileSize(msgVO.getImage().getFilesize());
                imageMsg.setCreatedTime(currentTime);
                imageMessages.add(imageMsg);
            } catch (Exception e) {
                log.error("批量处理单条图片消息失败, msgId: {}", baseMsg.getMsgId(), e);
                // 单条失败不影响整体批次，继续处理其他消息
            }
        }
        // 批量保存到数据库
        BatchSaveUtil.batchSave(imageMessages, imageMessageService::insertBatch, "图片消息");
//        if (!imageMessages.isEmpty()) {
//            try {
//                // 分批次保存，每批最多500条
//                int batchSize = 500;
//                for (int i = 0; i < imageMessages.size(); i += batchSize) {
//                    int end = Math.min(i + batchSize, imageMessages.size());
//                    List<QwImageMessage> subList = imageMessages.subList(i, end);
//                    imageMessageService.insertBatch(subList);
//                    log.info("已保存图片消息批次: {}-{}, 数量: {}", i, end - 1, subList.size());
//                }
//            } catch (Exception e) {
//                log.error("批量保存图片消息失败", e);
//                throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量保存图片消息失败");
//            }
//        }

    }

}